//
//  HomeController.m
//  MyBlog
//
//  Created by NCS on 16/12/2.
//  Copyright © 2016年 YSL. All rights reserved.
//

#import "HomeController.h"
#import "HomeCell.h"
#import "HomeCellModel.h"
#import "DetailViewController.h"
#import "YSLRefreshControl.h"

//const float COLLECTION_CELL_GAP = 10;
NSString *IDENTIFIER_HOME_DETAIL = @"ShowHomeDetail";

@implementation HomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   

    imageSize = DScreenWidth / 3 - 15;
    
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"circleData" ofType:@"plist"];
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"HomeData" ofType:@"plist"];
    
    self.listData = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    self.modelArr = [[NSMutableArray alloc] init];
    
    for (NSDictionary *dic in self.listData) {
        [self setModelData:dic];
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    
    // Refresh
    YSLRefreshControl *refresh = [[YSLRefreshControl alloc] init];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Loading"];
    [refresh addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    
    [self.refreshControl beginRefreshing];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
     NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"HomeData" ofType:@"plist"];
    self.listData = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    [self.tableView reloadData];
    
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    if (self.refreshControl.isRefreshing) {
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Loading..."];
        
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(addData) userInfo:nil repeats:NO];
//        [[NSRunLoop  currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [self addData];
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
        
        [self.tableView reloadData];
        [self.refreshControl endRefreshing];
        [NSDate distantPast];
    }
}

- (void)addData {
    NSLog(@"addData");
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"HomeData" ofType:@"plist"];
    NSDictionary *temp = [[[NSArray alloc] initWithContentsOfFile:plistPath] firstObject];
    [self insertModelData:temp index:0];

}

- (void)setModelData:(NSDictionary *)modelData {
    HomeCellModel *model = [[HomeCellModel alloc] initWithData:modelData];
    [self.modelArr addObject:model];
}

- (void)insertModelData:(NSDictionary *)modelData index:(int)index{
    HomeCellModel *model = [[HomeCellModel alloc] initWithData:modelData];
    [self.modelArr insertObject:model atIndex:index];
}

- (void)launchGuideView {
    self.guideViewController = [[GuideViewController alloc] initWithFrame:self.view.frame];
//    self.guideViewController.delegate = self;
    [self.view addSubview:self.guideViewController];
}

#pragma mark -- GuidePageDelegate
-(void)removeGuideView{
    [UIView animateWithDuration:0.5 animations:^{
        self.guideViewController.alpha = 0;
    } completion:^(BOOL finished) {
        [self.guideViewController removeFromSuperview];
    }];
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//    if ([segue.identifier isEqualToString:IDENTIFIER_HOME_DETAIL]) {
        DetailViewController *detailViewController = [segue destinationViewController];
        detailViewController.modal = ((HomeCell *)sender).homeCellModel;
//        self.tabBarController.hidesBottomBarWhenPushed = YES;
//        detailViewController.navigationItem.leftItemsSupplementBackButton = YES;
//    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}


#pragma mark -- TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.listData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCell" forIndexPath:indexPath];
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCell"];
    
    if (cell == nil) {
    
        cell = [[HomeCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"homeCell"];
    
    };
    
    HomeCellModel *data = self.modelArr[indexPath.row];
    
    cell.cellAvatar.image = [UIImage imageNamed:data.avatar];
    cell.cellName.text = data.name;
    cell.cellTime.text = data.time;
    cell.cellDevice.text = data.device;
    cell.cellContent.text = data.content;
    
    cell.dataIndex = indexPath;
    
    if (indexPath.row < self.modelArr.count) {
        cell.homeCellModel = self.modelArr[indexPath.row];
    }
    
    [cell setCellData:data];
    
    // Reset the height of the collection view
//    long imagesCount = [[data valueForKey:@"images"] count];
//    
//    if (imagesCount == 0) {
//        cell.collectionHeightConstraint.constant = 0;
//    } else if (imagesCount >= 1 && imagesCount <= 3){
//        cell.collectionHeightConstraint.constant = imageSize    ;
//    } else if (imagesCount > 3 && imagesCount <= 6){
//        cell.collectionHeightConstraint.constant = imageSize * 2 + COLLECTION_CELL_GAP;
//    } else if (imagesCount > 6 && imagesCount <= 9){
//        cell.collectionHeightConstraint.constant = imageSize  * 3 + COLLECTION_CELL_GAP * 3;
//    }
    
//    NSURL *url = [NSURL URLWithString:@"http://img3.imgtn.bdimg.com/it/u=3779691387,1388917972&fm=23&gp=0.jpg"];
//    [cell.cellAccessory sd_setImageWithURL:url];
    
    [cell updateConstraints];

//    [cell setGridImages:[self setImages]];
    [cell.cellImages reloadData];
    
    return cell;

    
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.tableView.estimatedRowHeight = 43;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    return self.tableView.rowHeight;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
//    
//    HomeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    [self performSegueWithIdentifier:IDENTIFIER_HOME_DETAIL sender:cell];
//}


//-(void)viewDidLayoutSubviews
//{
//    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
//        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
//    }
//    
//    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
//        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
//    }
//}
//
//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//        [cell setSeparatorInset:UIEdgeInsetsZero];
//    }
//    
//    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//        [cell setLayoutMargins:UIEdgeInsetsZero];
//    }
//}



@end
